package com.granada.behaviour.base;

import com.granada.entity.SysRole;
import com.granada.constants.Constant;
import com.granada.utils.MapperBeanUtils;
import com.granada.utils.ServiceBeanUtils;
import com.granada.vo.resp.PermissionRespNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public abstract class RoleBehavior implements com.granada.behaviour.interfaces.RoleBehavior {
    public void setheckced(List<PermissionRespNode> list, Set<Long> checkList){
        for(PermissionRespNode node:list){
            if(checkList.contains(node.getId())&&(node.getChildren()==null||node.getChildren().isEmpty())){
                node.setChecked(true);
            }
            setheckced((List<PermissionRespNode>) node.getChildren(),checkList);
        }
    }
    public void updateAfter(Long roleId) throws Exception {
        List<Long> userIds = MapperBeanUtils.getSysUserRoleMapper().getInfoByUserIdByRoleId(roleId);
        if(!userIds.isEmpty()){
            for (Long userId:userIds){
                ServiceBeanUtils.getRedisService().set(Constant.JWT_REFRESH_KEY +userId,userId,ServiceBeanUtils.getTokenSettings().getAccessTokenExpireTime().toMillis(), TimeUnit.MILLISECONDS);
                //清空权鉴缓存
                ServiceBeanUtils.getRedisService().delete(Constant.IDENTIFY_CACHE_KEY+userId);
            }
        }
    }

    public void deleteAfter(Long roleId) throws Exception{
        List<Long> userIds = MapperBeanUtils.getSysUserRoleMapper().getInfoByUserIdByRoleId(roleId);
        if(!userIds.isEmpty()){
            for (Long userId:userIds){
                ServiceBeanUtils.getRedisService().set(Constant.JWT_REFRESH_KEY +userId,userId,ServiceBeanUtils.getTokenSettings().getAccessTokenExpireTime().toMillis(), TimeUnit.MILLISECONDS);
                //清空权鉴缓存
                ServiceBeanUtils.getRedisService().delete(Constant.IDENTIFY_CACHE_KEY+userId);
            }
        }
    }

    public List<SysRole> getRoleInfoByUserId(Long userId) throws Exception {
        List<Long> roleIds = MapperBeanUtils.getSysUserRoleMapper().getRoleIdsByUserId(userId);
        if (roleIds.isEmpty()) {
            return null;
        }
        return MapperBeanUtils.getSysRoleMapper().getRoleInfoByIds(roleIds);
    }

    public List<String> getRoleNames(Long userId) throws Exception {
        List<SysRole> sysRoles = getRoleInfoByUserId(userId);
        if (null==sysRoles||sysRoles.isEmpty()){
            return null;
        }
        List<String> list=new ArrayList<>();
        for (SysRole sysRole:sysRoles){
            list.add(sysRole.getName());
        }
        return list;
    }

}
